package com.xrit.sunnyday.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xrit.sunnyday.dao.SetmealDao;
import com.xrit.sunnyday.entity.QueryPageBean;
import com.xrit.sunnyday.exception.SunnydayException;
import com.xrit.sunnyday.pojo.Setmeal;
import com.xrit.sunnyday.service.SetmealService;
import com.xrit.sunnyday.utils.QiNiuUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceIpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;

    /**
     * 查询所有（带分页）
     *
     * @param queryPageBean
     * @return
     */
    @Override
    public PageInfo<Setmeal> findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        if (!StringUtils.isEmpty(queryPageBean.getQueryString())) {
            queryPageBean.setQueryString("%" + queryPageBean.getQueryString() + "%");
        }
        List<Setmeal> setmealList = setmealDao.findPagesByCondition(queryPageBean.getQueryString());
        return new PageInfo<>(setmealList);
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        int count = setmealDao.findRole(id);
        if (count > 0) {
            throw new SunnydayException("该套餐关联了订单表数据!");
        }
        setmealDao.deleteSetmealAndCheckGroup(id);
        setmealDao.deleteById(id);
    }

    /**
     * 新增信息
     *
     * @param setmeal
     * @param checkgroupIds
     */
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        // 添加套餐信息
        setmealDao.add(setmeal);
        // 获取套餐的id
        Integer setmealId = setmeal.getId();
        // 添加套餐与检查组的关系
        if (null != checkgroupIds) {
            for (Integer checkgroupId : checkgroupIds) {
                setmealDao.addCheckGroupAndSetmeal(setmealId, checkgroupId);
            }
        }
//        FreeMarker处理
        generateMobileStaticHtml();
    }

    /**
     * 生成套餐列表、套餐具体详情静态页面
     */
    private void generateMobileStaticHtml() {
        try {
            //1.套餐列表静态页面
            generateSetmealListHtml();
            //2.套餐详情静态页面生成单个就行了，为了测试方便，生成所有的
            generateSetmealDetailHtml();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成套餐静态页面
     */
    private void generateSetmealListHtml() {
        String templateName = "mobile_setmeal.ftl";
        List<Setmeal> setmealList = setmealDao.findAll();
        setmealList.forEach(setmeal -> {
            setmeal.setImg(QiNiuUtils.DOMAIN + setmeal.getImg());
        });
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("setmealList", setmealList);
        String setmealListFile = out_put_path + "mobile_setmeal.html";
        generateHtml(templateName, dataMap, setmealListFile);
    }


    /**
     * 生成套餐详情静态页面
     */
    private void generateSetmealDetailHtml() {
        String templateName = "mobile_setmeal_detail.ftl";
        List<Setmeal> setmealList = setmealDao.findAll();
        for (Setmeal setmeal : setmealList) {
            Setmeal setmealDetail = setmealDao.findDetailById(setmeal.getId());
            setmealDetail.setImg(QiNiuUtils.DOMAIN + setmealDetail.getImg());
            Map<String, Object> dateMap = new HashMap<>();
            dateMap.put("setmeal",setmealDetail);
            String setmealListFile = out_put_path + "mobile_setmeal_" + setmealDetail.getId()+".html";
            generateHtml(templateName,dateMap,setmealListFile);
        }
    }


    /**
     * 编辑，查询套餐的id
     */
    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    /**
     * 编辑，根据套餐id查询检查组关联的数据
     */
    @Override
    public List<Integer> findSetmealAndCheckGroup(Integer id) {
        return setmealDao.findSetmealAndCheckGroup(id);
    }

    /**
     * 编辑，更改数据
     */
    @Override
    public void update(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.update(setmeal);//更改套餐的数据
        //根据套餐的id拿到和检查组关联的表，然后进行删除
        setmealDao.deleteSetmealAndCheckGroup(setmeal.getId());
        // 添加套餐与检查组的关系
        if (null != checkgroupIds) {
            for (Integer checkgroupId : checkgroupIds) {
                setmealDao.addCheckGroupAndSetmeal(setmeal.getId(), checkgroupId);
            }
        }
    }

    /**
     * 查出数据库中的所有图片
     *
     * @return
     */
    @Override
    public List<String> findImgs() {
        return setmealDao.findImgs();
    }

    /**
     * 查询所有
     */
    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    /**
     * 查询套餐详情
     */
    @Override
    public Setmeal findDetailById(Integer id) {
        return setmealDao.findDetailById(id);
    }

    @Autowired
    private FreeMarkerConfig freeMarkerConfig;
    @Value("${out_put_path}")
    private String out_put_path;

    /**
     * 封装生成静态页面的方法
     */
    private void generateHtml(String templateName, Map<String, Object> dataMap, String outFileName) {
        Configuration configuration = freeMarkerConfig.getConfiguration();
        BufferedWriter writer = null;
        try {
            Template template = configuration.getTemplate(templateName);
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFileName)));
            template.process(dataMap, writer);
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
